<template>
  <div class="download-ranking-container">
    <div class="ranking-header">
      <h3>共享文件下载榜</h3>
      <div class="ranking-actions">
        <button class="refresh-btn" @click="refreshRanking" :disabled="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </button>
      </div>
    </div>
    
    <div v-if="loading" class="loading-indicator">
      正在加载共享文件下载榜...
    </div>
    
    <div v-else-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-else-if="files.length === 0" class="empty-ranking">
      暂无共享文件数据。
      <div class="empty-actions">
        <button class="retry-btn" @click="refreshRanking">
          调试加载数据
        </button>
      </div>
    </div>
    
    <div v-else class="ranking-table-container">
      <table class="ranking-table">
        <thead>
          <tr>
            <th>排名</th>
            <th>文件名</th>
            <th>下载次数</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(file, index) in files" :key="index">
            <td class="rank-number">{{ index + 1 }}</td>
            <td class="file-name">
              <div style="display: flex; align-items: center; gap: 8px;">
              <div class="file-icon" :class="getFileIconClass( getFileExtension(file.filename))"></div>
              {{ file.filename }}
              </div>
            </td>
            <td class="download-count">{{ file.pv }}</td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <span>总计 {{ total }} 个文件</span>
        <div class="pagination-controls">
          <button 
            :disabled="currentPage <= 1"
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span>{{ currentPage }} / {{ totalPages }}</span>
          <button 
            :disabled="currentPage >= totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
    

  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import axios from 'axios';

// 状态变量
const files = ref([]);
const total = ref(0);
const loading = ref(false);
const error = ref('');
const currentPage = ref(1);
const pageSize = 10; // 每页显示的文件数量

// 文件预览相关状态
const showPreview = ref(false);
const previewingFile = ref(null);

// 计算总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(total.value / pageSize));
});

// 获取文件扩展名
const getFileExtension = (filename) => {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase();
};

// 获取文件图标类
const getFileIconClass = (fileType) => {
  if (!fileType || fileType === 'null') return 'file-icon';
  
  const typeMap = {
    'png': 'image-icon',
    'jpg': 'image-icon',
    'jpeg': 'image-icon',
    'gif': 'image-icon',
    'mp4': 'video-icon',
    'avi': 'video-icon',
    'mov': 'video-icon',
    'mp3': 'audio-icon',
    'wav': 'audio-icon',
    'pdf': 'pdf-icon',
    'doc': 'doc-icon',
    'docx': 'doc-icon',
    'xls': 'excel-icon',
    'xlsx': 'excel-icon',
    'txt': 'text-icon',
    'zip': 'archive-icon',
    'rar': 'archive-icon',
    'dll': 'binary-icon'
  };
  
  return typeMap[fileType.toLowerCase()] || 'file-icon';
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0 || !bytes) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 按照实际API响应格式处理数据
const processApiResponse = (data) => {
  if (!data || data.code !== 0) {
    console.error('API响应错误:', data);
    return false;
  }
  
  // 检查是否有文件列表
  if (data.files && Array.isArray(data.files)) {
    console.log(`接收到${data.files.length}个文件记录`);
    
    // 直接使用API返回的数据结构
    files.value = data.files;
    
    // 按下载次数排序
    files.value.sort((a, b) => parseInt(b.pv || 0) - parseInt(a.pv || 0));
    total.value = data.total || files.value.length;
    return true;
  }
  
  return false;
};

// 获取共享文件下载榜
const fetchRankingData = async () => {
  loading.value = true;
  error.value = '';
  
  console.log('开始请求共享文件下载榜数据');
  
  try {
    const token = localStorage.getItem('token');
    const user = localStorage.getItem('user');
    
    console.log('当前用户信息:', { token: token ? '已获取' : '未获取', user });
    
    if (!token) {
      error.value = '用户未登录或登录已过期';
      loading.value = false;
      return;
    }
    
    // 计算起始索引
    const start = (currentPage.value - 1) * pageSize;
    
    console.log(`获取下载榜数据，页码: ${currentPage.value}, 起始索引: ${start}, 每页数量: ${pageSize}`);
    
    // 构建请求数据
    const requestData = {
      count: pageSize,
      token: token,
      start: start
    };
    
    console.log('发送请求数据:', JSON.stringify(requestData));
    
    // 尝试使用不同的请求格式和参数组合
    try {
      // 发送请求
      console.log('发送第一种请求格式...');
      const response = await axios.post('/api/sharefiles?cmd=pvdesc', requestData);
      
      console.log('接收到响应数据:', response);
      console.log('响应状态:', response.status);
      console.log('响应数据详情:', JSON.stringify(response.data));
      
      if (processApiResponse(response.data)) {
        error.value = '';
        return; // 成功处理数据后返回
      }
    } catch (err) {
      console.error('获取共享文件下载榜请求错误:', err);
      if (err.response) {
        console.error('错误响应状态:', err.response.status);
        console.error('错误响应数据:', JSON.stringify(err.response.data));
      }
      error.value = `网络错误: ${err.message}`;
    }
  } finally {
    loading.value = false;
  }
};

// 切换页码
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
  fetchRankingData();
};

// 文件操作函数
const previewFile = (file) => {
  // 保存预览文件信息并显示预览对话框
  previewingFile.value = file;
  showPreview.value = true;
};

const closePreview = () => {
  showPreview.value = false;
  setTimeout(() => {
    previewingFile.value = null;
  }, 300); // 等待关闭动画结束后清除文件
};

const downloadFile = async (file) => {
  try {
    // 检查是否有URL
    if (!file.url || file.url === '#') {
      showCenterNotification('文件URL不可用，无法下载', 'error');
      return;
    }

    // 创建下载链接并执行下载
    const a = document.createElement('a');
    a.href = file.url;
    a.download = file.file_name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    
    // 下载后更新文件访问计数
    const user = localStorage.getItem('user');
    
    if (!user) {
      console.error('获取用户信息失败，无法更新文件下载计数');
      return;
    }
    
    // 检查是否有必要的MD5值
    if (!file.md5) {
      console.error('文件缺少MD5值，无法更新计数');
      showCenterNotification('下载成功，但无法更新统计数据', 'warning');
      return;
    }
    
    // 构建请求数据
    const requestData = {
      filename: file.file_name,
      md5: file.md5,
      user: user
    };
    
    console.log('更新文件下载计数请求:', requestData);
    
    // 发送更新计数请求
    const response = await axios.post('/api/dealsharefile?cmd=pv', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('更新文件下载计数响应:', response.data);
    
    if (response.data.code === 0) {
      // 更新成功，本地更新计数
      file.pv = (parseInt(file.pv) || 0) + 1;
      showCenterNotification('下载成功', 'success');
    } else {
      console.error('更新文件下载计数失败:', response.data);
    }
  } catch (err) {
    console.error('下载文件或更新计数出错:', err);
    showCenterNotification('下载过程中发生错误', 'error');
  }
};

// 显示中央通知
const showCenterNotification = (message, type = 'success') => {
  // 创建一个通知元素
  const notificationElement = document.createElement('div');
  notificationElement.className = `center-notification ${type}`;
  
  // 设置内容
  notificationElement.innerHTML = `
    <div class="center-notification-content">
      <span class="center-notification-icon">${type === 'success' ? '✅' : '❌'}</span>
      <span class="center-notification-message">${message}</span>
    </div>
  `;
  
  // 添加到DOM
  document.body.appendChild(notificationElement);
  
  // 添加动画类
  setTimeout(() => {
    notificationElement.classList.add('show');
  }, 10);
  
  // 设置自动消失
  setTimeout(() => {
    notificationElement.classList.remove('show');
    notificationElement.classList.add('hide');
    
    // 动画结束后移除元素
    setTimeout(() => {
      if (document.body.contains(notificationElement)) {
        document.body.removeChild(notificationElement);
      }
    }, 300);
  }, 3000);
};

// 初始加载
onMounted(() => {
  console.log('下载榜组件已挂载');
  initializeComponent();
  
  // 监听刷新事件
  window.addEventListener('refresh-download-ranking', handleRefresh);
});

// 组件初始化
const initializeComponent = async () => {
  console.log('正在初始化下载榜组件...');
  
  // 先清空现有数据
  files.value = [];
  
  // 尝试调试获取数据
  await debugFetchRanking();
  
  // 延迟检查数据加载情况
  setTimeout(() => {
    if (files.value.length === 0 && !loading.value) {
      console.log('初始化后没有数据，尝试再次加载');
      debugFetchRanking();
    }
  }, 1000);
};

// 处理全局刷新事件
const handleRefresh = () => {
  console.log('收到下载榜刷新事件');
  debugFetchRanking();
};

// 组件销毁时清理事件监听
onUnmounted(() => {
  window.removeEventListener('refresh-download-ranking', handleRefresh);
});

// 刷新按钮点击事件
const refreshRanking = () => {
  console.log('手动刷新按钮被点击');
  debugFetchRanking();
};

// 调试专用获取数据函数，尝试多种格式
const debugFetchRanking = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      error.value = '用户未登录';
      return;
    }
    
    console.log('-------- 开始调试请求 --------');
    
    // 基本请求数据
    const reqData = {
      count: pageSize,
      token: token,
      start: 0
    };
    
    // 尝试格式1：直接使用axios默认设置
    try {
      console.log('尝试格式1: axios默认设置');
      const resp1 = await axios.post('/api/sharefiles?cmd=pvdesc', reqData);
      console.log('格式1响应:', resp1.status, resp1.data);
      if (processApiResponse(resp1.data)) {
        console.log('格式1成功处理数据!');
        return;
      }
    } catch (e) {
      console.error('格式1失败:', e.message);
    }
    
    // 尝试格式2：指定Content-Type
    try {
      console.log('尝试格式2: 指定Content-Type');
      const resp2 = await axios.post('/api/sharefiles?cmd=pvdesc', reqData, {
        headers: { 'Content-Type': 'application/json' }
      });
      console.log('格式2响应:', resp2.status, resp2.data);
      if (processApiResponse(resp2.data)) {
        console.log('格式2成功处理数据!');
        return;
      }
    } catch (e) {
      console.error('格式2失败:', e.message);
    }
    
    // 尝试格式3：字符串化请求体
    try {
      console.log('尝试格式3: 字符串化请求体');
      const resp3 = await axios.post('/api/sharefiles?cmd=pvdesc', JSON.stringify(reqData), {
        headers: { 'Content-Type': 'application/json' }
      });
      console.log('格式3响应:', resp3.status, resp3.data);
      if (processApiResponse(resp3.data)) {
        console.log('格式3成功处理数据!');
        return;
      }
    } catch (e) {
      console.error('格式3失败:', e.message);
    }
    
    // 尝试格式4：完全自定义请求
    try {
      console.log('尝试格式4: XMLHttpRequest');
      await new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/sharefiles?cmd=pvdesc', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = function() {
          if (xhr.status === 200) {
            console.log('格式4响应:', xhr.responseText);
            try {
              const data = JSON.parse(xhr.responseText);
              if (processApiResponse(data)) {
                console.log('格式4成功处理数据!');
              }
            } catch (e) {
              console.error('解析XHR响应失败:', e);
            }
          }
          resolve();
        };
        xhr.send(JSON.stringify(reqData));
      });
    } catch (e) {
      console.error('格式4失败:', e.message);
    }
    
    console.log('-------- 调试请求结束 --------');
    
    // 如果到这里还没有数据，显示错误
    if (files.value.length === 0) {
      error.value = '无法获取数据，请检查网络连接';
    }
    
  } catch (err) {
    console.error('调试请求错误:', err);
    error.value = '请求错误';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.download-ranking-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  position: relative;
}

.ranking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.ranking-header h3 {
  margin: 0;
  font-size: 18px;
}

.ranking-actions {
  display: flex;
  gap: 10px;
}

.refresh-btn {
  padding: 8px 15px;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.refresh-btn:hover {
  background-color: #e0e0e0;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-indicator,
.error-message,
.empty-ranking {
  padding: 30px;
  text-align: center;
  color: #666;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.empty-ranking {
  padding: 30px;
  text-align: center;
  color: #666;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.empty-actions {
  margin-top: 15px;
}

.retry-btn {
  padding: 8px 15px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.retry-btn:hover {
  background-color: #1976d2;
}

.error-message {
  color: #f44336;
}

.ranking-table-container {
  width: 100%;
  overflow-x: auto;
}

.ranking-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.ranking-table th,
.ranking-table td {
  text-align: left;
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
}

.ranking-table th {
  background-color: #f5f5f5;
  font-weight: 500;
  color: #333;
}

.ranking-table tr:hover {
  background-color: #f9f9f9;
}

.rank-number {
  font-weight: bold;
  text-align: center;
  width: 60px;
}

.rank-number:nth-child(1) {
  color: #f57f17;
  width: 100px;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-icon {
  width: 20px;
  height: 20px;
  background-color: #ddd;
  border-radius: 2px;
}

.image-icon { background-color: #81c784; }
.video-icon { background-color: #64b5f6; }
.audio-icon { background-color: #9575cd; }
.pdf-icon { background-color: #e57373; }
.doc-icon { background-color: #4fc3f7; }
.excel-icon { background-color: #66bb6a; }
.text-icon { background-color: #9e9e9e; }
.archive-icon { background-color: #ffb74d; }
.binary-icon { background-color: #ba68c8; }
/* .file-icon { background-color: #9e9e9e; } */

.download-count {
  font-weight: bold;
  color: #2196f3;
}

.actions-cell {
  display: flex;
  gap: 5px;
  white-space: nowrap;
}

.action-btn {
  padding: 6px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

.action-btn:hover {
  background-color: #f0f0f0;
}

.preview-btn {
  color: #2196f3;
}

.download-btn {
  color: #4caf50;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-controls button {
  padding: 5px 10px;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .ranking-table {
    font-size: 14px;
  }
  
  .ranking-table th,
  .ranking-table td {
    padding: 10px;
  }
}
</style> 